import { message } from "antd";
import { routerRedux } from "dva/router";
import toTreeData from "./getTree";
import apis from "./pushPlanApi";

const {
  getSceneList,
  getPushApp,
  getPushWay,
  getTrigger,
  getPushObjType,
  getPlanTable,
  getPlanDetail,
  deletePlan,
  updateStatus,
  addPlan,
  getOrg
} = apis;

const initialFilter = {
  order: "",
  status: "",
  comments: "",
  pageIndex: 1,
  pageSize: 10
};

export default {
  namespace: "pushPlan",
  state: {
    tableLoading: false,
    pushPlanList: [], // 查询结果
    planId: "", // 编辑计划id
    planDetail: {}, // 编辑详情数据
    staticData: {
      sceneList: [],
      pushAppList: [],
      pushWayList: [],
      triggerList: [],
      objectTypeList: [],
      orgTree: []
    }, // 编辑详情页静态数据
    effTime: null, // 保存自定义开始是按
    expTime: null, // 保存自定义结束时间
    pushTimes: null, // 保存推送时间
    timesUnit: "day", // 保存推送时间单位
    filter: initialFilter, // 表单查询过滤器
    totalCount: 0, // 总数
    totalPage: 1 // 总页数
  },
  effects: {
    // 获取静态数据
    *getStaticData(empty, { call, put }) {
      const { data: sceneList = [] } = yield call(getSceneList);
      const { data: pushAppList = [] } = yield call(getPushApp);
      const { data: pushWayList = [] } = yield call(getPushWay);
      const { data: objectTypeList = [] } = yield call(getPushObjType);
      const { datas: orgList = [] } = yield call(getOrg);
      const orgTree = toTreeData(orgList);
      yield put({
        type: "saveStaticData",
        payload: {
          sceneList,
          pushAppList,
          pushWayList,
          objectTypeList,
          orgTree
        }
      });
    },
    *getTrigger({ payload }, { call, put }) {
      const { data: triggerList = [] } = yield call(getTrigger, payload);
      yield put({
        type: "saveStaticData/triggerList",
        payload: {
          triggerList
        }
      });
    },
    // 获取表格
    *getPlanTable({ payload }, { call, put, select }) {
      const filterCache = yield select(({ pushPlan: { filter } }) => filter);
      const params = { ...filterCache, ...payload };
      yield put({ type: "saveFilter", payload: params });
      yield put({ type: "tableLoading", payload: true });
      const { data, totalCount, totalPage } = yield call(getPlanTable, params);
      yield put({ type: "tableLoading", payload: false });
      yield put({
        type: "savePlanList",
        payload: { data, totalCount, totalPage }
      });
    },

    // 获取计划详情
    *getPlanDetail({ payload }, { call, put }) {
      const { errCode, data } = yield call(getPlanDetail, payload);
      if (errCode === 0) {
        yield put({
          type: "saveDetail",
          payload: data
        });
        yield put(routerRedux.push("/pushPlan/pushPlanEdit"));
      }
    },

    // 删除计划
    *deletePlan({ payload }, { call, put }) {
      const { errCode } = yield call(deletePlan, payload);
      if (errCode === 0) {
        yield put({ type: "getPlanTable" });
      } else {
        message.error("删除失败");
      }
    },
    // 启用/停用计划
    *triggerStatus({ payload }, { call, put }) {
      const { errCode } = yield call(updateStatus, payload);
      if (errCode === 0) {
        yield put({ type: "getPlanTable" });
      } else {
        message.error("操作失败");
      }
    },

    // 保存/修改计划
    *addPlan({ payload }, { call, put, select }) {
      let correct = true;
      const id = yield select(({ pushPlan: { planId } }) => planId);
      let params = payload;
      if (payload.periodType === "自定义") {
        const eff = yield select(({ pushPlan: { effTime } }) => effTime);
        const exp = yield select(({ pushPlan: { expTime } }) => expTime);
        if (eff && exp) params = { ...params, effTime: eff, expTime: exp };
        else {
          message.error("请输入自定义时间");
          correct = false;
        }
      }
      if (payload.timeType === "自定义") {
        const times = yield select(({ pushPlan: { pushTimes } }) => pushTimes);
        const unit = yield select(({ pushPlan: { timesUnit } }) => timesUnit);
        if (times && unit)
          params = { ...params, pushTimes: times, timesUnit: unit };
        else {
          message.error("请输入自定义频率");
          correct = false;
        }
      }
      // 表单验证正确后发请求
      if (correct) {
        // 新增或修改判断
        if (id) params = { ...params, id };
        const { errCode } = yield call(addPlan, params);
        if (errCode === 0) yield put(routerRedux.push("/pushPlan"));
        else message.error("操作失败");
      }
    }
  },
  reducers: {
    // 存储静态数据
    saveStaticData: (state, { payload }) => ({
      ...state,
      staticData: { ...state.staticData, ...payload }
    }),
    "saveStaticData/triggerList": (state, { payload }) => ({
      ...state,
      staticData: { ...state.staticData, ...payload }
    }),
    // 存储过滤器
    saveFilter: (state, { payload }) => ({
      ...state,
      filter: payload
    }),
    // 存储计划列表
    savePlanList: (state, { payload: { data, totalCount, totalPage } }) => ({
      ...state,
      pushPlanList: data,
      totalCount,
      totalPage
    }),
    // 保存详情
    saveDetail: (state, { payload }) => ({
      ...state,
      planDetail: payload,
      planId: payload.id,
      effTime: payload.effTime,
      expTime: payload.expTime,
      pushTimes: payload.pushTimes || null,
      timesUnit: payload.timesUnit || "day"
    }),
    // 表格加载Loading改变
    tableLoading: (state, { payload }) => ({
      ...state,
      tableLoading: payload
    }),
    // 清除查询过滤器内容
    clearFilter: state => ({
      ...state,
      filter: initialFilter
    }),
    // 清楚详情缓存
    clearDetail: state => ({
      ...state,
      planDetail: {},
      planId: "",
      effTime: null,
      expTime: null,
      pushTimes: null
    }),
    // 改变时间
    changeTime: (state, { payload }) => ({
      ...state,
      effTime: payload.effTime,
      expTime: payload.expTime
    }),
    // 改变频率数值
    changePushTimes: (state, { payload }) => ({
      ...state,
      pushTimes: payload
    }),
    // 改变频率单位
    changeTimesUnit: (state, { payload }) => ({
      ...state,
      timesUnit: payload
    })
  }
};
